import React, { useState } from 'react'
import { Table, Tag } from 'antd';
import type { TableProps } from 'antd';
import { Input, Space, Modal, Form, Select } from 'antd';


import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { Flex, message, Upload } from 'antd';
import type { GetProp, UploadProps } from 'antd';

import { updateworksinfo, updateads, deleteads, updateadsinfo } from '../../../../request/api'
export default function User_content(props) {
    const { userdata, getuserlist } = props;


    let [_id, set_id] = useState('')
    let [name, setname] = useState([])//名称
    let [sort, setsort] = useState([])//排序
    let [state, setstate] = useState([])//状态
    let [location, setlocation] = useState([])//位置
    let [img, setimg] = useState('')//图片
    let [type, settype] = useState('')//类型
    const [modal2Open, setModal2Open] = useState(false); //控制模态框是否显示


    const columns: TableProps<DataType>['columns'] = [
        {
            title: '广告名称',
            key: 'name',
            dataIndex: 'name',
        },
        {
            title: '图片',
            key: 'name',
            dataIndex: 'name',
            render: (_, record) => (
                <img style={{ width: '50px' }} src={record.image}></img>
            ),
        },
        {
            title: '广告位置',
            dataIndex: 'location',
            key: 'location',
        },
        {
            title: '时间',
            dataIndex: 'add_Time',
            key: 'add_Time',
        },
        {
            title: '点击次数',
            dataIndex: 'count',
            key: 'count',
        },
        {
            title: '状态',
            dataIndex: 'state',
            key: 'state',
        },

        {
            title: '操作',
            key: 'action',
            render: (_, record) => (
                <Space size="middle">
                    <a onClick={() => {
                        datatags(record)
                    }}>编辑</a>
                    <a onClick={() => {
                        updatastate(record.key, record.state)
                    }}>{record.state == '上线' ? '下线' : '上线'}</a>
                    <a onClick={() => {
                        Deleteworks(record.key)
                    }}>删除</a>
                </Space>
            ),
        },
    ];
    // 修改状态
    const updatastate = async (_id: string, state: boolean) => {
        let from = {
            _id: _id,
            state: state
        }
        let data = await updateads(from)
        if (data.code == 200) {
            alert('修改状态成功')
            getuserlist(data.code)
        }
    }
    // 删除数据
    const Deleteworks = async (_id: string) => {
        let data = await deleteads({ _id: _id })
        if (data.code == 200) {
            alert('删除成功')
            getuserlist(data.code)
        }
    }

    // 数据展示
    let dataSource = userdata.map(item => ({
        key: item._id,
        name: item.name,
        location: item.location,
        sort: item.sort,
        add_Time: item.add_Time,
        state: item.state == true ? '上线' : '下线',
        type: item.type,
        image: item.img,
        count: item.count,
    }));

    const [componentSize, setComponentSize] = useState<SizeType | 'default'>('default');
    const onFormLayoutChange = ({ size }: { size: SizeType }) => {
        setComponentSize(size);
    };

    // 数据回显
    const datatags = (item: any) => {
        setModal2Open(true)
        setname(item.name)
        setsort(item.sort)
        setstate(item.state)
        set_id(item.key)
        setlocation(item.location)
        settype(item.type)
        setImageUrl(item.image)

    }

    // 修改标签
    const tagsupdata = async () => {
        let from = {
            _id: _id,
            name: name,
            sort: sort,
            state: state,
            location: location,
            type: type,
            img: img,
            add_Time: new Date().toLocaleString()
        }
        let res = await updateadsinfo({ from: from })
        if (res.code == 200) {
            alert('修改成功')
            getuserlist(res.code)
            setModal2Open(false)
        }
    }



    // 图片
    type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];

    const getBase64 = (img: FileType, callback: (url: string) => void) => {
        const reader = new FileReader(); // FileReader对象用于读取文件
        reader.addEventListener('load', () => callback(reader.result as string)); // 读取文件
        reader.readAsDataURL(img); // 转base64
    };

    const beforeUpload = (file: FileType) => {
        // return isJpgOrPng && isLt2M;
    };
    const [loading, setLoading] = useState(false);
    const [imageUrl, setImageUrl] = useState<string>();

    const handleChange: UploadProps['onChange'] = (info) => {
        if (info.file.status === 'uploading') { // 上传中
            setLoading(true);
            return;
        }
        if (info.file.status === 'done') { // 上传完成
            // Get this url from response in real world.
            getBase64(info.file.originFileObj as FileType, (url) => {
                setLoading(false); // 上传完成
                setImageUrl(url); // 设置图片
                setimg(info.file.response.img) // 设置图片地址
            });
        }
    };

    const uploadButton = (
        <button style={{ border: 0, background: 'none' }} type="button">
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div style={{ marginTop: 8 }}>Upload</div>
        </button> //这里需要修改成你想要的样式
    );



    return (
        <div>
            <Table<DataType> columns={columns} dataSource={dataSource} />
            <Modal
                title='修改标签'
                centered
                open={modal2Open}
                onOk={() => tagsupdata()}
                onCancel={() => setModal2Open(false)}
            >
                <Form
                    labelCol={{ span: 6 }}
                    wrapperCol={{ span: 14 }}
                    layout="horizontal"
                    initialValues={{ size: componentSize }}
                    onValuesChange={onFormLayoutChange}
                    size={componentSize as SizeType}
                    style={{ maxWidth: 600 }}
                >
                    <Form.Item label="广告名称">
                        <Input value={name} onChange={(e) => {
                            setname(e.target.value)
                        }} />
                    </Form.Item>
                    <Form.Item label="广告位置">
                        <Select value={location} onChange={(e) => {
                            setlocation(e)
                        }}>
                            <Select.Option value='首页轮播图'>首页轮播图</Select.Option>
                            <Select.Option value='首页推荐位置'>首页推荐位置</Select.Option>
                        </Select>
                    </Form.Item>
                    <Form.Item label="排序">
                        <Input value={sort} onChange={(e) => {
                            setsort(e.target.value)
                        }} />
                    </Form.Item>
                    <Form.Item label="状态" >
                        <Select value={state} onChange={(e) => {
                            setstate(e)
                        }}>
                            <Select.Option value='true'>上线</Select.Option>
                            <Select.Option value='false'>下线</Select.Option>
                        </Select>
                    </Form.Item>
                    <Form.Item label="广告图片">
                        <Upload
                            name="avatar" // 上传的文件字段名
                            listType="picture-card" // 上传列表的内建样式，支持 picture-card 和 picture
                            className="avatar-uploader" // 上传列表类名
                            showUploadList={false} // 是否展示 uploadList
                            action="http://localhost:3000/content/index/imgupload" // 上传的地址
                            beforeUpload={beforeUpload} // 上传前处理
                            onChange={handleChange} // 上传中处理
                        >
                            {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
                        </Upload>
                    </Form.Item>
                    <Form.Item label="跳转类型" >
                        <Select value={type} onChange={(e) => {
                            settype(e)
                        }}>
                            <Select.Option value='站内'>站内</Select.Option>
                            <Select.Option value='外链'>外链</Select.Option>
                        </Select>
                    </Form.Item>
                </Form>

            </Modal>
        </div>
    )
}
